import Global from '../global/global.js'
/**
 * 玩家类
 */
export default class Player {

  constructor (ctx) {
    this.x = canvas.width / 2,
    this.y = 550
    this.width = 80
    this.height = 60
    this.imgName = 'player'
    this.centerX = 80 / 2
    this.centerY = 60 / 2
    this.ctx = ctx

    // 绑定移动事件
    wx.onTouchMove(this.bindMoveEvent.bind(this))
    wx.onTouchStart(this.bindMoveEvent.bind(this))
  }

  /**
   * 根据坐标将图形画到页面上
   */
  draw(ctx) {
    let x = this.x - this.centerX
    // ctx.fillStyle = '#990000'
    // ctx.fillRect(x, this.y, this.width, this.height)
    // 替换图片
    let imgObj = Global._ImgObj[this.imgName]
    if (imgObj) {
      ctx.drawImage(imgObj, 0, 30, imgObj.width, imgObj.height - 90, x, this.y, this.width, this.height);
    }
  }

  /**
   * 绑定触摸移动事件
   */
  bindMoveEvent (res) {
    // 校验游戏是否结束
    if (Global.overGame) {
      wx.offTouchStart(this.bindMoveEvent)
      wx.offTouchMove(this.bindMoveEvent)
      return
    }

    // 触摸位置
    let touchX = res.touches[0].clientX
    let touchY = res.touches[0].clientY

    let x = this.x
    let y = this.y

    // 判断触摸开始时是否在方块内，不在的情况，移动时每次都要校验位置，在中心时则可随意移动，解决了移动快时角色跟不上的问题
    if (res.type == "touchstart" || this.isNoCenter) {
      // 触摸位置必须在方块内
      if (!(x - this.centerX <= touchX && touchX <= x + this.centerX && y <= touchY && touchY <= y + this.height)
        || (res.type != "touchstart" && this.isNoCenter)) {
        this.isNoCenter = true
        return
      }
      this.isNoCenter = false
    }

    // 不能超出屏幕
    touchX = touchX < 0 ? 0 : touchX
    touchX = touchX > canvas.width ? canvas.width : touchX
    touchY = touchY < 0 ? 0 : touchY
    touchY = touchY > canvas.height ? canvas.height : touchY

    // 设置新的位置
    this.x = touchX
    this.y = touchY - this.centerY
    this.draw(this.ctx)
  }
}